﻿using System;
using System.Windows.Data;
using System.Globalization;

namespace StockholmsStad.Windows.UI.Infrastructure.Converters
{
    public sealed class PersonalNumberConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof(string))
                throw new InvalidOperationException("The target must be a string");

            if(value != null)
            {
                var number = (string)value;

                if (number.Length > 8 && !number.Contains("-"))
                    return number.Insert(8, "-");
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof(string))
                throw new InvalidOperationException("The target must be a string");

            if (value != null)
            {
                var number = (string)value;

                if (number.Length > 8 && !number.Contains("-"))
                    return number.Insert(8, "-");
            }

            return value;
        }

        #endregion
    }
}